package pay;

import pay.util.payService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import java.io.IOException;

@WebServlet("/pay")
public class userPayServlet extends HttpServlet {
    //用户发起支付请求,此时还未支付
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        int user_id = (int)session.getAttribute("userId"); // 从session中获取user_id
        String order_id = payService.generateOrderId(user_id);  // 订单号

        String shopname = req.getParameter("shopName"); // 商品名称
        String totalAmountStr = req.getParameter("totalAmount"); // 商品金额

        double money;
        try {
            money = Double.parseDouble(totalAmountStr);
        } catch (NumberFormatException e) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "参数 totalAmount 格式错误");
            return;
        }
        try {
            payService.userPay(order_id, shopname, money, resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "支付处理出错");
        }
    }

}